package com.beiye.drivertransport.SubActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.adapter.ListBaseAdapter;
import com.beiye.drivertransport.adapter.SuperViewHolder;
import com.beiye.drivertransport.bean.IllegalLearningitemBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.githang.statusbar.StatusBarCompat;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;



import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

//违章学习
public class IllegalLearningActivity extends TwoBaseAty {

    ImageView img_illegalback;//返回

    TextView tv_illegal;
    //    @Bind(R.id.img_illegal)
//    TextView img_illegal;

    LRecyclerView lv_illegal;

    View empty_view;

    TextView tv_illegal1;

    TextView title;
    //    private PopWindowApt popWindowApt;
//    private PopupWindow mPopWindow;
//    ArrayList<LoginUserBean.DataBean.CurUserOrgBean> cusList = new ArrayList<>();
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private int firstIndex = 1;
    private int pageSize = 10;
    private IllegalLearningApt illegalLearningApt;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    private String jumpType;

    @Override
    public int getLayoutId() {
        return R.layout.activity_illegal_learning;

    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_illegalback) {
            SharedPreferences sp = getSharedPreferences("IllegalLearningActivity", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.clear();
            edit.commit();
            finish();
        } else if (id == R.id.tv_illegal1) {
            if (Utils.isFastClicker()) {
                return;
            }
            SharedPreferences sp1 = getSharedPreferences("IllegalLearningActivity", Context.MODE_PRIVATE);
            String orgId = sp1.getString("orgId", "");
            String adId = sp1.getString("adId", "");

            Bundle bundle = new Bundle();
            bundle.putString("adId", adId);
            bundle.putString("orgId", orgId);
            bundle.putString("jumpType", jumpType);
            startActivity(TypesofViolationTrainingActivity.class, bundle);
        }

    }

//    private void showPopupWindow() {
//        //设置contentView
//        View contentView = LayoutInflater.from(IllegalLearningActivity.this).inflate(R.layout.popwindow_layout, null);
//        mPopWindow = new PopupWindow(contentView,
//                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
//        //设置各个控件的点击响应
//        ListView lv_company = (ListView) contentView.findViewById(R.id.lv_company);
//        lv_company.setAdapter(popWindowApt);
//
//        mPopWindow.showAtLocation(tv_illegal, Gravity.CENTER, 0, 0);
//
//        lv_company.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//                if (popWindowApt != null) {
//
//                    String orgName = popWindowApt.getItem(position).getOrgName();
//                    String orgId = popWindowApt.getItem(position).getOrgId();
//                    String adId = popWindowApt.getItem(position).getAdId();
//                    int mark = popWindowApt.getItem(position).getMark();
//                    mPopWindow.dismiss();
//                    tv_illegal.setText(orgName);
//                    SharedPreferences sp =getSharedPreferences("IllegalLearningActivity",
//                            Context.MODE_PRIVATE);
//                    SharedPreferences.Editor editor1 = sp.edit();
//                    editor1.putString("orgId", orgId);
//                    editor1.putString("adId", adId);
//                    editor1.putInt("mark", mark);
//                    editor1.commit();
//                    requestData();
//                }
//            }
//        });
//
//
//    }


    @Override
    public void initData() {
        img_illegalback = (ImageView)findViewById(R.id.img_illegalback);
        tv_illegal = (TextView) findViewById(R.id.tv_illegal);
        lv_illegal = (LRecyclerView) findViewById(R.id.lv_illegal);
        empty_view = (View) findViewById(R.id.empty_view);
        tv_illegal1 = (TextView) findViewById(R.id.tv_illegal1);
        title = (TextView) findViewById(R.id.title);

        //   LoginUserBean userInfo = UserManger.getUserInfo();
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));

        Bundle bundle = getIntent().getExtras();
        String orgId = bundle.getString("orgId");
        String adId = bundle.getString("adId");
        String orgName = bundle.getString("orgName");
        jumpType = bundle.getString("jumpType");
        tv_illegal.setText(orgName);
        SharedPreferences sp = getSharedPreferences("IllegalLearningActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = sp.edit();
        editor1.putString("orgId", orgId);
        editor1.putString("adId", adId);
        editor1.commit();

        if (jumpType.equals("homeFgt")) {
            tv_illegal1.setVisibility(View.VISIBLE);
            title.setText("违章学习列表");
            tv_illegal1.setText("申请违章培训");
        }else{
            title.setText("信用修复");
            tv_illegal1.setText("申请");
        }

        initCompany();
        initUi();
    }

    private void initUi() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(IllegalLearningActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lv_illegal.setLayoutManager(layoutManager);
        illegalLearningApt = new IllegalLearningApt(IllegalLearningActivity.this);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(illegalLearningApt);
        lv_illegal.setAdapter(lRecyclerViewAdapter);
        lv_illegal.setFooterViewColor(R.color.colorAccent, R.color.dark, android.R.color.white);
        lv_illegal.setFooterViewHint("拼命加载中", "已经全部为你呈现了", "网络不给力啊，点击再试一次吧");
        lv_illegal.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                firstIndex = 1;
                requestData();
            }
        });

        lv_illegal.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore() {

                firstIndex += pageSize;
                requestData();
            }
        });
        empty_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lv_illegal.refresh();
            }
        });

        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (Utils.isFastClicker()) {
                    return;
                }
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(IllegalLearningActivity.this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(IllegalLearningActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                    return;
                }


                int uvtSn = illegalLearningApt.getDataList().get(position).getSn();
//                SharedPreferences sp = getSharedPreferences("IllegalLearningActivity",
//                        Context.MODE_PRIVATE);
//                int mark = sp.getInt("mark", 1);
                Bundle bundle = new Bundle();
                bundle.putInt("uvtSn", uvtSn);
                bundle.putString("jumpType", jumpType);
//                bundle.putInt("mark", mark);
                startActivity(SubIllegalLearningActivity.class, bundle);
            }
        });
        lv_illegal.refresh();

    }

    private void initCompany() {

//        LoginUserBean.DataBean data = userInfo.getData();
//        if (data == null) {
//            return;
//        }
//        List<LoginUserBean.DataBean.CurUserOrgBean> curuserOrglist = data.getCur_userOrg();
//        if (curuserOrglist.size() == 0) {
//            img_illegal.setVisibility(View.INVISIBLE);
//            return;
//        }
//        cusList.clear();
//        for (int i = 0; i < curuserOrglist.size(); i++) {
//            if (curuserOrglist.get(i).getMark() != 2) {
//                cusList.add(curuserOrglist.get(i));
//            }
//        }
//        if (cusList.size() == 0) {
//            img_illegal.setVisibility(View.INVISIBLE);
//            SharedPreferences sppp =getSharedPreferences("Mark", Context.MODE_PRIVATE);
//            SharedPreferences.Editor editor2 = sppp.edit();
//            editor2.putInt("Mark", 2);
//            editor2.commit();
//            tv_illegal.setText("");
//            return;
//        }
//
//        String orgName = cusList.get(0).getOrgName();
//        String orgId = cusList.get(0).getOrgId();
//        String adId = cusList.get(0).getAdId();
//        int mark = cusList.get(0).getMark();



        lv_illegal.refresh();
        requestData();
//        popWindowApt = new PopWindowApt(IllegalLearningActivity.this, cusList, R.layout.popwindow_item_layout);
//
//        if (popWindowApt.getCount() == 1) {
//            img_illegal.setVisibility(View.INVISIBLE);
//        } else {
//            img_illegal.setVisibility(View.VISIBLE);
//        }

    }

    @Override
    public void onBackPressed() {
        SharedPreferences sp = getSharedPreferences("IllegalLearningActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();
        super.onBackPressed();
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {
            IllegalLearningitemBean illegalLearningitemBean = JSON.parseObject(result, IllegalLearningitemBean.class);
            if (!jumpType.equals("homeFgt")) {
                if (illegalLearningitemBean.getRows().size() > 0) {
                    tv_illegal1.setVisibility(View.GONE);
                }else{
                    tv_illegal1.setVisibility(View.VISIBLE);
                }
            }
            if (illegalLearningitemBean != null) {
                try {
                    if (illegalLearningitemBean.getRows() != null && illegalLearningitemBean.getRows().size() > 0) {
                        lv_illegal.setVisibility(View.VISIBLE);
                        if (firstIndex == 1) {
                            illegalLearningApt.clear();
                            illegalLearningApt.setDataList(illegalLearningitemBean.getRows());
                        } else {
                            illegalLearningApt.addAll(illegalLearningitemBean.getRows());
                        }

                        if (illegalLearningitemBean.getRows().size() < pageSize) {
                            lv_illegal.setNoMore(true);
                        }
                    } else {
                        if (firstIndex == 1) {//第一页
                            lv_illegal.setEmptyView(empty_view);
                            illegalLearningApt.clear();
                        } else {
                            lv_illegal.setNoMore(true);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                lv_illegal.refreshComplete(illegalLearningitemBean.getRows() == null ? 0 : illegalLearningitemBean.getRows().size());
                lRecyclerViewAdapter.notifyDataSetChanged();
            }

        }
        super.onSuccess(result, call, response, what);
    }

    @Override
    protected void onResume() {
        lv_illegal.refresh();
        requestData();
        super.onResume();
    }

    @Override
    public void requestData() {
        SharedPreferences sp = getSharedPreferences("IllegalLearningActivity", Context.MODE_PRIVATE);
        String orgId = sp.getString("orgId", "");
        String adId = sp.getString("adId", "");

        SharedPreferences dishSp = getSharedPreferences("BusinessSelfinspectionDishinfoActivity", Context.MODE_PRIVATE);
        String discreditId = dishSp.getString("discreditId", "");

        SharedPreferences eduListSp = getSharedPreferences("BusinessSelfinspectionScoreEducListActivity", Context.MODE_PRIVATE);
        String scoreEducId = eduListSp.getString("scoreEducId", "");

        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();

        if (jumpType.equals("homeFgt")) {
            new Login().getIllegalData(adId, orgId, userId, firstIndex, pageSize, this, 1);
        } else if (jumpType.equals("dish")) {
            scoreEducId = "";
            new Login().vioTrainFindById(discreditId, scoreEducId, this, 1);
        } else {
            discreditId = "";
            new Login().vioTrainFindById(discreditId, scoreEducId, this, 1);
        }


    }

    public class IllegalLearningApt extends ListBaseAdapter<IllegalLearningitemBean.RowsBean> {

        protected Context context = null;
        protected String datestr;


        public IllegalLearningApt(Context context) {
            super(context);
            this.context = context;
        }

        @Override
        public int getLayoutId() {
            return R.layout.illegal_item_layout;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_date = holder.getView(R.id.tv_illegal);//创建日期
            TextView tv_sign = holder.getView(R.id.tv_illegal1);//签名
            TextView tv_learnphoto = holder.getView(R.id.tv_illegal2);//学习图片
            TextView tv_desc = holder.getView(R.id.tv_illegal3);//违章描述
            ImageView img_over = holder.getView(R.id.img_illegal);//是否完成
            ImageView img_sign = holder.getView(R.id.img_illegal1);//是否签名
            ImageView img_shenhe = holder.getView(R.id.img_illegal2);//是否审核
            ImageView img_shotshenhe = holder.getView(R.id.img_illegal3);//是否抽查
            long creationDate = getDataList().get(position).getCreationDate();
            if (creationDate > 0) {
                Date date = new Date(creationDate);
                try {
                    //yyyy表示年MM表示月dd表示日
                    //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                    //进行格式化
                    datestr = sdf.format(date);
                    if (jumpType.equals("homeFgt")) {
                        tv_date.setText(datestr + "违章学习");
                    }else{
                        tv_date.setText(datestr+"信用修复学习");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                tv_date.setText("");

            }

            int checkMark = getDataList().get(position).getCheckMark();
            int finishMark = getDataList().get(position).getFinishMark();
            if (checkMark == 2) {
                tv_learnphoto.setVisibility(View.VISIBLE);
                tv_learnphoto.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int sn = getDataList().get(position).getSn();
                        Bundle bundle = new Bundle();
                        bundle.putInt("sn", sn);
                        startActivity(LearnphotoActivity.class, bundle);
                    }
                });
                tv_sign.setVisibility(View.VISIBLE);
                tv_sign.setText("查看签名");
                img_over.setImageResource(R.mipmap.bj_11);
                img_shenhe.setVisibility(View.VISIBLE);
                img_shenhe.setImageResource(R.mipmap.bj_21);
                img_sign.setVisibility(View.VISIBLE);
                img_sign.setImageResource(R.mipmap.bj_111);
                tv_sign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isFastDoubleClick()) {
                            return;
                        }
//                        String signPicUrl = getDataList().get(position).getSignPicUrl();
//                        Bundle bundle = new Bundle();
//                        bundle.putString("signPicUrl", signPicUrl);
                        int sn = getDataList().get(position).getSn();
                        String signPicUrl = getDataList().get(position).getSignPicUrl();
                        Bundle bundle = new Bundle();
                        bundle.putInt("sn", sn);
                        bundle.putString("signPicUrl", signPicUrl);
                        startActivity(SignillegallearningActivity.class, bundle);
                    }
                });

            } else if (checkMark == 1) {
                tv_learnphoto.setVisibility(View.VISIBLE);
                tv_learnphoto.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int sn = getDataList().get(position).getSn();
                        Bundle bundle = new Bundle();
                        bundle.putInt("sn", sn);
                        startActivity(LearnphotoActivity.class, bundle);
                    }
                });
                tv_sign.setVisibility(View.VISIBLE);
                tv_sign.setText("查看签名");
                img_over.setImageResource(R.mipmap.bj_11);
                img_shenhe.setVisibility(View.VISIBLE);
                img_shenhe.setImageResource(R.mipmap.bj_09);
                img_sign.setVisibility(View.VISIBLE);
                img_sign.setImageResource(R.mipmap.bj_111);
                tv_sign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isFastDoubleClick()) {
                            return;
                        }
//                        String signPicUrl =getDataList().get(position).getSignPicUrl();
//                        Bundle bundle = new Bundle();
//                        bundle.putString("signPicUrl", signPicUrl);
//                        //startActivity(SignCourseActivity.class, bundle);
                        int sn = getDataList().get(position).getSn();
                        String signPicUrl = getDataList().get(position).getSignPicUrl();
                        Bundle bundle = new Bundle();
                        bundle.putInt("sn", sn);
                        bundle.putString("signPicUrl", signPicUrl);
                        startActivity(SignillegallearningActivity.class, bundle);
                    }
                });

            } else if (checkMark == 0) {

                if (finishMark == 1) {
                    tv_learnphoto.setVisibility(View.VISIBLE);
                    tv_learnphoto.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            int sn = getDataList().get(position).getSn();
                            Bundle bundle = new Bundle();
                            bundle.putInt("sn", sn);
                            startActivity(LearnphotoActivity.class, bundle);
                        }
                    });
                    img_over.setImageResource(R.mipmap.bj_11);
//                if(rowsBean.getPjtMark()==1)//判断是否是岗前培训
//                {
//                    tv_complesign.setVisibility(View.GONE);
//                    record_parent_sign.setVisibility(View.GONE);//签名按钮
//
//                }else{
                    img_shenhe.setVisibility(View.VISIBLE);
                    img_shenhe.setImageResource(R.mipmap.bj_03);
                    img_sign.setVisibility(View.VISIBLE);
                    img_sign.setImageResource(R.mipmap.bj_112);//未签名
                    tv_sign.setVisibility(View.VISIBLE);//签名按钮
                    tv_sign.setText("签名");

                    tv_sign.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isFastDoubleClick()) {
                                return;
                            }
                            int sn = getDataList().get(position).getSn();
                            Bundle bundle = new Bundle();
                            bundle.putInt("sn", sn);
                            bundle.putString("signPicUrl", "");
                            startActivity(SignillegallearningActivity.class, bundle);
                        }
                    });


                } else if (finishMark == 2) {
                    tv_learnphoto.setVisibility(View.VISIBLE);
                    tv_learnphoto.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            int sn = getDataList().get(position).getSn();
                            Bundle bundle = new Bundle();
                            bundle.putInt("sn", sn);
                            startActivity(LearnphotoActivity.class, bundle);
                        }
                    });
                    img_over.setImageResource(R.mipmap.bj_11);
//                if(rowsBean.getPjtMark()==1)//判断是否是岗前培训
//                {
//                    tv_complesign.setVisibility(View.GONE);
//                    record_parent_sign.setVisibility(View.GONE);//签名按钮
//                }else {
                    img_shenhe.setVisibility(View.VISIBLE);
                    img_shenhe.setImageResource(R.mipmap.bj_03);
                    img_sign.setVisibility(View.VISIBLE);
                    img_sign.setImageResource(R.mipmap.bj_111);//已签名
                    tv_sign.setVisibility(View.VISIBLE);//签名按钮
                    tv_sign.setText("查看签名");
                    tv_sign.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isFastDoubleClick()) {
                                return;
                            }
                            int sn = getDataList().get(position).getSn();
                            String signPicUrl = getDataList().get(position).getSignPicUrl();
                            Bundle bundle = new Bundle();
                            bundle.putInt("sn", sn);
                            bundle.putString("signPicUrl", signPicUrl);
                            startActivity(SignillegallearningActivity.class, bundle);
                        }
                    });

                } else if (finishMark == 0) {
                    tv_learnphoto.setVisibility(View.GONE);
                    img_over.setImageResource(R.mipmap.bj_23);
//                if(rowsBean.getPjtMark()==1)//判断是否是岗前培训
//                {
//                    tv_complesign.setVisibility(View.GONE);
//                    record_parent_sign.setVisibility(View.GONE);//签名按钮
//                }else {
                    img_shenhe.setVisibility(View.GONE);
                    img_sign.setVisibility(View.GONE);
                    tv_sign.setVisibility(View.GONE);

                }

            }
            int spotCheckMark = getDataList().get(position).getSpotCheckMark();
            if (spotCheckMark == 1) {
                img_shotshenhe.setVisibility(View.VISIBLE);
                img_shotshenhe.setImageResource(R.mipmap.bj_07);
            } else if (spotCheckMark == 2) {
                img_shotshenhe.setVisibility(View.VISIBLE);
                img_shotshenhe.setImageResource(R.mipmap.bj_19);
            } else {
                img_shotshenhe.setVisibility(View.GONE);
            }
            String violationDesc = getDataList().get(position).getViolationDesc();

            if (jumpType.equals("homeFgt")) {
                if (violationDesc == null) {
                    String str = "违章描述: " + "";
                    SpannableString spannableString = new SpannableString(str);
                    spannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    tv_desc.setText(spannableString);
                } else {
                    String str = "违章描述: " + violationDesc;
                    SpannableString spannableString = new SpannableString(str);
                    spannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    tv_desc.setText(spannableString);
                }
            }else{
                if (violationDesc == null) {
                    String str = "失信行为描述: " + "";
                    SpannableString spannableString = new SpannableString(str);
                    spannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    tv_desc.setText(spannableString);
                } else {
                    String str = "失信行为描述: " + violationDesc;
                    SpannableString spannableString = new SpannableString(str);
                    spannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    tv_desc.setText(spannableString);
                }
            }


        }
    }
}
